package com.haitaoit.chengquan.module.home.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.main.ShowOutLine;
import com.haitaoit.chengquan.module.home.activity.maintenance.MaintenanceDetailActivity2;
import com.haitaoit.chengquan.module.home.adapter.QCreditSearchAdapter;
import com.haitaoit.chengquan.module.home.model.CreditSearchModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 信誉查询
 */
public class CreditSearchActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pullrefreshscrollview)
    PullToRefreshScrollView pullrefreshscrollview;

    private ScrollView mScrollView;
    private LinearLayout null_information_layout;
    private MyListView listView;
    private EditText credit_et;

    private boolean isFrist = true;
    private int page = 1;

    private QCreditSearchAdapter adapter;
//    private PopupWindow myPopWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pullrefreshscollview);
        ViewUtils.inject(this);


        View view = LayoutInflater.from(this).inflate(R.layout.activity_credit_search, null);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);
        credit_et = (EditText) view.findViewById(R.id.credit_et);
        credit_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH){
                    startSearch();
                    return true;
                }
                return false;
            }
        });
        view.findViewById(R.id.left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        view.findViewById(R.id.search_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {// 收起键盘
                startSearch();
            }
        });

        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(false);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new QCreditSearchAdapter(this);
        adapter.setBackCall(backCall);
        listView.setAdapter(adapter);
    }

    private void startSearch() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(credit_et.getWindowToken(), 0);
        if (credit_et.getText().toString().equals("")) {
            ToastUtils.showToast("输入内容不能为空！");
        } else {
            isFrist = true;
            page = 1;
            httpGetuser_credit_rating_list();
//                    iniPopupWindow();
//                    myPopWindow.showAsDropDown(((ImageView) view.findViewById(R.id.search_img)), 0, 0);
        }
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            switch (which) {
                case R.id.brand_itemll:
                    Intent intent;
                    if("1".equals(adapter.getList().get((Integer) obj[0]).getUser_type())){
                        intent = new Intent(CreditSearchActivity.this, CreditSearchDetailActivity.class);
                        intent.putExtra("id", adapter.getList().get((Integer) obj[0]).getId());
                        intent.putExtra("user_type",adapter.getList().get((Integer) obj[0]).getUser_type());
                    }else{
                        intent = new Intent(CreditSearchActivity.this, MaintenanceDetailActivity2.class);
                        intent.putExtra("id", adapter.getList().get((Integer) obj[0]).getId());
                    }
                    startActivity(intent);
                    break;
                case R.id.got_out_of_line:
                    Intent intent1 = new Intent();
                    intent1.setClass(CreditSearchActivity.this, ShowOutLine.class);
                    intent1.putExtra("id", adapter.getList().get((Integer) obj[0]).getId());
                    startActivity(intent1);
                    break;
            }
            super.deal(which, obj);
        }
    };


    //    // 弹出框
//    private void iniPopupWindow() {
//        View layout = LayoutInflater.from(this).inflate(R.layout.search, null);
//        View.OnClickListener listener = new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                switch (v.getId()) {
//                    case R.id.select_look:// 需求商查询
//                        search_type = 1;
//                        break;
//                    case R.id.select_time:// 服务商查询
//                        search_type = 2;
//                        break;
//                }
//                isFrist = true;
//                page = 1;
//                if (search_type == 1) {
//                    httpGetuser_credit_rating_list(Constant.Getuser_credit_rating_list);
//                } else if (search_type == 2) {
//                    httpGetuser_credit_rating_list(Constant.Getmer_credit_rating_list);
//                }
//                myPopWindow.dismiss();
//            }
//        };
//        layout.findViewById(R.id.select_look).setOnClickListener(listener);
//        layout.findViewById(R.id.select_time).setOnClickListener(listener);
//
//        myPopWindow = new PopupWindow(layout);
//        myPopWindow.setFocusable(true); // 加上这个popupwindow中的ListView才可以接收点击事件
//        // 控制popupwindow 的宽度和高度
//        myPopWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
//        myPopWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//
//        // 控制popupwindow 点击屏幕其他地方消失
//        myPopWindow.setBackgroundDrawable(this.getResources().getDrawable(R.color.transparent)); // 设置背景图片,不能在布局中设置，要通过代码来设置
//        myPopWindow.setOutsideTouchable(true);// 触摸popupwindow外部,popupwindow消失,这个要求你的popupwindow要有背景图片才可以成功
//    }

    private void httpGetuser_credit_rating_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("name", credit_et.getText().toString()));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("name", credit_et.getText().toString());
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);
        showDailog("");
        HttpUtilsSingle.doGet(this, false, Constant.Getmer_credit_rating_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                hindDailog();
                String result = arg0.result.toString();
                List<CreditSearchModel> new_list = new ArrayList<CreditSearchModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<CreditSearchModel>();

                            break;
                        case 0:// 成功

                            System.out.println(Response);
                            System.out.println(Response);
                            System.out.println(Response);
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<CreditSearchModel>>() {
                                    }.getType());

                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<CreditSearchModel>();

                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<CreditSearchModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                hindDailog();
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<CreditSearchModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        if (credit_et.getText().toString().equals("")) {
            ToastUtils.showToast("输入内容不能为空！");
        } else {
            httpGetuser_credit_rating_list();
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        if (credit_et.getText().toString().equals("")) {
            ToastUtils.showToast("输入内容不能为空！");
        } else {
            httpGetuser_credit_rating_list();
        }
    }
}
